const http = require('http');
const request = require('request-json');

const utils = require('../common/utils');

module.exports = class extends think.Service {
    send(list) {
        return new Promise(resolve => {
            let smsKey = 'hhOoPzr6hMxVqE6yiB4j211qYkc7f84K';
            let param = {
                'msgType': 0,
                'smsUser': 'iforyou',
                'templateId': 746297,
                'phone': list.phone,
                'vars': `{%smscode%:"${list.code}"}`
            };

            let sorted_param = utils.sortDict(param);

            let param_str = '';
            for (let key in sorted_param) {
                param_str += (key + '=' + sorted_param[key] + '&');
            }
            param_str = smsKey + '&' + param_str + smsKey;
            let sign = utils.md5(param_str);
            param['signature'] = sign.toUpperCase();

            let data = require('querystring').stringify(param);
            let options = {
                host: 'www.sendcloud.net',
                port: 80,
                path: '/smsapi/send',
                method: 'POST'
            };
            options.path = options.path + '?' + data;

            const req = http.request(options, function(res) {
                let responseStr = '';
                res.on('data', function(chunk) {
                    responseStr += chunk;
                });
                res.on('end', function() {
                    resolve(JSON.parse(responseStr));
                });
            });
            req.end();
        });
    }
};
